package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.*;

import java.util.concurrent.Executors;

/**
 * 任务取消和回退
 *
 * @author yangyunjiao
 */
public class FallbackExample {
    public static void main(String[] args) {
        ListeningExecutorService executor =
                MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));

        ListenableFuture<String> primaryTask = executor.submit(() -> {
            throw new RuntimeException("主任务失败");
        });

        // 设置回退任务
        ListenableFuture<String> fallbackFuture = Futures.catchingAsync(
                primaryTask,
                Throwable.class,
                throwable -> executor.submit(() -> "回退任务结果"),
                MoreExecutors.directExecutor()
        );

        Futures.addCallback(fallbackFuture, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("最终结果: " + result);
            }

            @Override
            public void onFailure(Throwable t) {
                System.err.println("所有任务都失败了: " + t.getMessage());
            }
        }, MoreExecutors.directExecutor());
    }
}
